package com.apimarket.security;

import com.alibaba.fastjson.JSON;
import com.apimarket.entity.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:AuthenticationEntryPoint主要用来处理匿名用户访问无权限资源时的异常(未登陆，登陆状态过期失效)
 * @Author ZXR
 * @Date 2021/7/20 14:10
 * @Version 1.0
 * 前台拿到这个错误后就可以做一些处理，主要是退出到登录页面
 */
@Component
public class CustomizeAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse
            , AuthenticationException e) throws IOException, ServletException {
        Result<String> result=new Result<>("用户未登录",400,"fail");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}
